import os

class Shard(object):
  def __init__(self, fname, shard_idx, start_row_idx, end_row_idx):
    self.fname = fname
    self.shard_idx = shard_idx
    self.start_row_idx = start_row_idx
    self.end_row_idx = end_row_idx

  def _ShardFileName(self):
    """Creates shard filename."""
    return self.fname + "_" + self.shard_idx

  def Open(self):
    self._fd = open(self._ShardFileName(), "w")
    # TODO: Support appends

  def Close(self):
    self._fd.close()

  def Accept(self, row_idx):
    """Does this shard handle the 'row_idx'th data."""
    return self.start_row_idx <= row_idx < self.end_row_idx

  def WriteLine(self, s):
    """Write s as a separate line. 
    
    All leading and trailing white spaces are ignored.
    """
    self._fd.write(s.strip() + os.linesep)

  def WriteLines(self, lines):
    for l in lines:
      self.WriteLines(l)
